function filenan = gs_savecond(filena,ext,boxname)
%
%           === CONDITIONED SAVING OPTIONS ===
%
%filenan = gs_savecond(filena)
%
% If 'filena' is a string with extension '.mat', the function verifies 
% the existence of the file whose name is 'filena'. If the file does not
% exists, the combo box for the file selcetion is shown.
% The filename 'filena' can contain the file path.
% If the file already exists, three options are presented: 
%   1) overwriting; 
%   2) saving with another filename. A dialog box named 'FILENAME' appears;
%   3) no save. 
% In the third case, filena is empty.
%
%filenan = gs_savecond(filena,ext)
%
% As above, but the extension 'ext' is considered. If 'filena' is
% extensionless, or its extension is different from 'ext', the 
% extension 'ext' is added. For example, is 'ext' is 'mat',
% 'filena.mat' is considered.
%
%filenan = gs_savecond(filena,boxname)
%
% The string 'boxname', having at least three characters, in this
% case is considered as name of the dialog box if the option 2) appears.
%
%filenan = gs_savecond(filena,ext,boxname)
%
% In this case, the two possibilities as above are combined.
%
% This function does not perform the data saving, which is instead 
% operated calling SAVE od DLMREAD. Simply, this function allow the
% management of data saving conditions.

% G. Teza, 2007.

if nargin < 1 || isempty(filena)
    filena = ''; 
end
if ~ischar(filena)
    filenan = []; 
    return; 
end

if nargin == 2
    if length(ext) <= 3
        boxname = 'FILENAME';
    else
        boxname = ext; 
        ext = '.mat';
    end
end
if nargin == 1
    ext = '.mat'; 
    boxname = 'FILENAME'; 
end

[fi,pa] = uiputfile(ext,boxname,filena);
if fi ~= 0
    filenan = fullfile(pa,fi);
else
    filenan = [];
end